package com.oneraku.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.oneraku.service.dao.WorkOrderCommentMapper;
import com.oneraku.service.domain.UserInfo;
import com.oneraku.service.domain.WorkOrder;
import com.oneraku.service.dao.WorkOrderMapper;
import com.oneraku.service.domain.WorkOrderComment;
import com.oneraku.service.dto.WorkOrderCommentInfo;
import com.oneraku.service.exceptions.InfoException;
import com.oneraku.service.service.IUserInfoService;
import com.oneraku.service.service.IWorkOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oneraku.service.utils.AuthBean;
import com.oneraku.service.utils.R;
import com.oneraku.service.utils.RequestUserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单 服务实现类
 * </p>
 *
 * @author renhui <337375464@qq.com>
 * @since 2020-02-25
 */
@Service
public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder> implements IWorkOrderService {
    private WorkOrderCommentMapper workOrderCommentMapper;
    private IUserInfoService userInfoService;
    @Autowired
    public WorkOrderServiceImpl(WorkOrderCommentMapper workOrderCommentMapper,IUserInfoService userInfoService) {
        this.workOrderCommentMapper = workOrderCommentMapper;
        this.userInfoService = userInfoService;
    }
    private void checkWorkOrder(WorkOrder workOrder){
        if(StringUtils.isEmpty(workOrder.getCategory())){
            throw new InfoException("工单类型未知");
        }
    }
    @Override
    public R listWorkOrder(WorkOrder workOrder) {
        AuthBean authBean = RequestUserUtils.getUser();
        return R.okPage(page(workOrder.page(), Wrappers.<WorkOrder>lambdaQuery().eq(WorkOrder::getCreator,authBean.getId()).orderByDesc(WorkOrder::getCreateTime)));
    }
    @Override
    public R addWorkOrder(WorkOrder workOrder) {
        checkWorkOrder(workOrder);
        AuthBean authBean = RequestUserUtils.getUser();
        WorkOrder storeWorkOrder = new WorkOrder();
        storeWorkOrder.setCategory(workOrder.getCategory());
        storeWorkOrder.setSummary(workOrder.getSummary());
        storeWorkOrder.setImages(workOrder.getImages());
        storeWorkOrder.setCreator(authBean.getId());
        return R.ok(save(storeWorkOrder));
    }
    @Override
    public R delWorkOrder(WorkOrderComment workOrderComment) {
        if(StringUtils.isEmpty(workOrderComment.getId())){
            throw new InfoException("删除标识未知！");
        }
        AuthBean authBean = RequestUserUtils.getUser();
        WorkOrder localWorkOrder = getById(workOrderComment.getId());
        if(null == localWorkOrder){
            throw new InfoException("未找到相关的对象");
        }
        if(!localWorkOrder.getCreator().equals(authBean.getId())){
            throw new InfoException("无权限删除该工单");
        }
        workOrderCommentMapper.delete(new QueryWrapper<WorkOrderComment>().lambda().eq(WorkOrderComment::getWorkOrderId,localWorkOrder.getId()));
        return R.ok(removeById(localWorkOrder.getId()));
    }
    @Override
    public R comments(WorkOrderComment workOrderComment) {
        String workOrderId = workOrderComment.getWorkOrderId();
        AuthBean authBean = RequestUserUtils.getUser();
        if(StringUtils.isEmpty(workOrderId)){
            throw new InfoException("工单id不能为空！");
        }
        WorkOrder workOrder = getById(workOrderId);
        if(null == workOrder || !workOrder.getCreator().equals(authBean.getId())){
            throw new InfoException("未找到相关的工单信息！");
        }
        List<WorkOrderComment> commentList = workOrderCommentMapper.selectList(Wrappers.<WorkOrderComment>lambdaQuery().eq(WorkOrderComment::getWorkOrderId,workOrderId));
        Set<String> uids = commentList.stream().map(item->item.getUid()).collect(Collectors.toSet());
        if(uids.size() == 0){
            return R.ok(Collections.emptyList());
        }
        List<UserInfo>  userInfos =  userInfoService.list(Wrappers.<UserInfo>lambdaQuery()
                .select(UserInfo::getId,UserInfo::getName,UserInfo::getAvatar)
                .in(UserInfo::getId,uids)
        );
        Map<String,UserInfo> userInfoMap = new HashMap<String,UserInfo>();
        userInfos.forEach(item->userInfoMap.put(item.getId(),item));
        List<WorkOrderCommentInfo> commentInfos = commentList.stream().map(item->{
            UserInfo userInfo = userInfoMap.get(item.getUid());
            if(null == userInfo){
                return item.toInfo("","");
            } else {
                return item.toInfo(userInfo.getName(),userInfo.getAvatar());
            }
        }).collect(Collectors.toList());
        workOrderCommentMapper.
                update(null,
                        Wrappers.<WorkOrderComment>lambdaUpdate()
                        .set(WorkOrderComment::getRead,Boolean.TRUE)
                        .eq(WorkOrderComment::getWorkOrderId,workOrderId)
                        .eq(WorkOrderComment::getType,"sys"));
        return R.ok(commentInfos);
    }
    @Override
    @Transactional
    public R addComments(WorkOrderComment workOrderComment) {
        String workOrderId = workOrderComment.getWorkOrderId();
        AuthBean authBean = RequestUserUtils.getUser();
        if(StringUtils.isEmpty(workOrderId)){
            throw new InfoException("缺少工单参数");
        }
        WorkOrder workOrder = getById(workOrderId);
        if(workOrder.getResolved()){
            throw new InfoException("工单已解决无法评论！");
        }
        if(!workOrder.getCreator().equals(authBean.getId())){
            throw new InfoException("无权限评论该工单!");
        }
        if(StringUtils.isEmpty(workOrderComment.getTxt())){
            throw new InfoException("评论内容不能为空");
        }
        if(workOrderComment.getResovled()){
            update(Wrappers.<WorkOrder>lambdaUpdate()
                    .set(WorkOrder::getResolved,true)
                    .set(WorkOrder::getStar,workOrderComment.getStar())
                    .set(WorkOrder::getNotice,workOrder.getNotice() + 1)
                    .eq(WorkOrder::getId,workOrderId));
        }
        workOrderComment.setRead(false);
        workOrderComment.setType("usr");
        workOrderComment.setUid(authBean.getId());
        workOrderCommentMapper.insert(workOrderComment);
        return R.ok("success");
    }
}
